package cn.com.gzheroli.bfw.web.system.controler.core;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;

import cn.com.gzheroli.bfw.pojo.base.TSAttachment;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.controller.BaseController;
import cn.com.gzheroli.core.common.model.common.UploadFile;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ImportFile;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.FileUtils;
import cn.com.gzheroli.core.util.JSONHelper;
import cn.com.gzheroli.core.util.MyClassLoader;
import cn.com.gzheroli.core.util.ReflectHelper;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.core.util.mybatis.SqlMapper;
import cn.com.gzheroli.tag.core.DataGrid;
import cn.com.gzheroli.tag.vo.easyui.Autocomplete;
import cn.com.gzheroli.util.TagUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


/**
 * 通用业务处理
 * 
 * 
 */
@Controller
@RequestMapping("/commonController")
public class CommonController  {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CommonController.class);
	@Autowired
	private SystemService systemService;
	@Autowired
	private CommonService commonService;
	@Autowired
	SqlMapper sqlMapper;
	private String message;
	@Autowired
    private SpringRedisCache cache;

	/**
	 * 通用列表页面跳转
	 */
	@RequestMapping(params = "listTurn")
	public ModelAndView listTurn(HttpServletRequest request) {
		String turn = request.getParameter("turn");// 跳转的目标页面
		return new ModelAndView(turn);
	}

	/**
	 * 附件预览页面打开链接
	 * 
	 * @return
	 */
	@RequestMapping(params = "openViewFile")
	public ModelAndView openViewFile(HttpServletRequest request) {
		String fileid = request.getParameter("fileid");
		String subclassname = oConvertUtils.getString(request.getParameter("subclassname"), "cn.com.gzheroli.bfw.pojo.base.TSAttachment");
		String contentfield = oConvertUtils.getString(request.getParameter("contentfield"));
		//Class fileClass = MyClassLoader.getClassByScn(subclassname);// 附件的实际类
		
		Object fileobj = commonService.get(TSAttachment.class, fileid);
		ReflectHelper reflectHelper = new ReflectHelper(fileobj);
		String extend = oConvertUtils.getString(reflectHelper.getMethodValue("extend"));
		if ("dwg".equals(extend)) {
			String realpath = oConvertUtils.getString(reflectHelper.getMethodValue("realpath"));
			request.setAttribute("realpath", realpath);
			return new ModelAndView("common/upload/dwgView");
		} else if (FileUtils.isPicture(extend)) {
			String realpath = oConvertUtils.getString(reflectHelper.getMethodValue("realpath"));
			request.setAttribute("realpath", realpath);
			request.setAttribute("fileid", fileid);
			request.setAttribute("subclassname", subclassname);
			request.setAttribute("contentfield", contentfield);
			return new ModelAndView("common/upload/imageView");
		} else {
			String swfpath = oConvertUtils.getString(reflectHelper.getMethodValue("swfpath"));
			request.setAttribute("swfpath", swfpath);
			return new ModelAndView("common/upload/swfView");
		}

	}

	/**
	 * 附件预览读取
	 * 
	 * @return
	 */
	@RequestMapping(params = "viewFile")
	public void viewFile(HttpServletRequest request, HttpServletResponse response) {
		String fileid =oConvertUtils.getString(request.getParameter("fileid"));
		String subclassname = oConvertUtils.getString(request.getParameter("subclassname"), "cn.com.gzheroli.bfw.pojo.base.TSAttachment");
		//Class fileClass = MyClassLoader.getClassByScn(subclassname);// 附件的实际类

		Object fileobj = commonService.get(TSAttachment.class, fileid);
		ReflectHelper reflectHelper = new ReflectHelper(fileobj);
		UploadFile uploadFile = new UploadFile(request, response);
		String contentfield = oConvertUtils.getString(request.getParameter("contentfield"), uploadFile.getByteField());
		byte[] content = (byte[]) reflectHelper.getMethodValue(contentfield);
		String path = oConvertUtils.getString(reflectHelper.getMethodValue("realpath"));
		String extend = oConvertUtils.getString(reflectHelper.getMethodValue("extend"));
		String attachmenttitle = oConvertUtils.getString(reflectHelper.getMethodValue("attachmenttitle"));
		uploadFile.setExtend(extend);
		uploadFile.setTitleField(attachmenttitle);
		uploadFile.setRealPath(path);
		uploadFile.setContent(content);
		//uploadFile.setView(true);
		systemService.viewOrDownloadFile(uploadFile);
	}

	@RequestMapping(params = "importdata")
	public ModelAndView importdata() {
		return new ModelAndView("system/upload");
	}

	/**
	 * 生成XML文件
	 * 
	 * @return
	 */
	@RequestMapping(params = "createxml")
	public void createxml(HttpServletRequest request, HttpServletResponse response) {
		String field = request.getParameter("field");
		String entityname = request.getParameter("entityname");
		ImportFile importFile = new ImportFile(request, response);
		importFile.setField(field);
		importFile.setEntityName(entityname);
		importFile.setFileName(entityname + ".bak");
		importFile.setEntityClass(MyClassLoader.getClassByScn(entityname));
		systemService.createXml(importFile);
	}

	/**
	 * 生成XML文件parserXml
	 * 
	 * @return
	 */
	@RequestMapping(params = "parserXml")
	@ResponseBody
	public AjaxJson parserXml(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson json = new AjaxJson();
		String fileName = null;
		UploadFile uploadFile = new UploadFile(request);
		String ctxPath = request.getSession().getServletContext().getRealPath("");
		File file = new File(ctxPath);
		if (!file.exists()) {
			file.mkdir();// 创建文件根目录
		}
		MultipartHttpServletRequest multipartRequest = uploadFile.getMultipartRequest();
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile mf = entity.getValue();// 获取上传文件对象
			fileName = mf.getOriginalFilename();// 获取文件名
			String savePath = file.getPath() + "/" + fileName;
			File savefile = new File(savePath);
			try {
				FileCopyUtils.copy(mf.getBytes(), savefile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		systemService.parserXml(ctxPath + "/" + fileName);
		json.setSuccess(true);
		return json;
	}

	/**
	 * 自动完成请求返回数据
	 * 
	 * @param request
	 * @param responss
	 */
	/*@RequestMapping(params = "getAutoList")
	public void getAutoList(HttpServletRequest request, HttpServletResponse response, Autocomplete autocomplete) {
		String jsonp = request.getParameter("jsonpcallback");
		String trem = StringUtil.getEncodePra(request.getParameter("trem"));// 重新解析参数
		autocomplete.setTrem(trem);
		List autoList = systemService.getAutoList(autocomplete);
		String labelFields = autocomplete.getLabelField();
		String[] fieldArr = labelFields.split(",");
		String valueField = autocomplete.getValueField();
		String[] allFieldArr = null;
		if (StringUtil.isNotEmpty(valueField)) {
			allFieldArr = new String[fieldArr.length+1];
			for (int i=0; i<fieldArr.length; i++) {
				allFieldArr[i] = fieldArr[i];
			}
			allFieldArr[fieldArr.length] = valueField;
		}
		
		try {
			String str = TagUtil.getAutoList(autocomplete, autoList);
			str = "(" + str + ")";
			response.setContentType("application/json;charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(JSONHelper.listtojson(allFieldArr,allFieldArr.length,autoList));
            response.getWriter().flush();
            response.getWriter().close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}*/

	
	

	/**
	 * 继承于TSAttachment附件公共列表数据
	 */
	@RequestMapping(params = "objfileGrid")
	public void objfileGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		String businessKey = oConvertUtils.getString(request.getParameter("businessKey"));
		String subclassname = oConvertUtils.getString(request.getParameter("subclassname"));// 子类类名
		final String type = oConvertUtils.getString(request.getParameter("typename"));
		final String code = oConvertUtils.getString(request.getParameter("typecode"));
		final String filekey = oConvertUtils.getString(request.getParameter("filekey"));
		/*CriteriaQuery cq = new CriteriaQuery(MyClassLoader.getClassByScn(subclassname), dataGrid);
		cq.eq("businessKey", businessKey);
		if (StringUtil.isNotEmpty(type)) {
			cq.createAlias("TBInfotype", "TBInfotype");
			cq.eq("TBInfotype.typename", type);
		}
		if (StringUtil.isNotEmpty(filekey)) {
			cq.eq("id", filekey);
		}
		if (StringUtil.isNotEmpty(code)) {
			cq.createAlias("TBInfotype", "TBInfotype");
			cq.eq("TBInfotype.typecode", code);
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);*/
		Map para=new HashMap();
		para.put("businessKey", businessKey);
		para.put("filekey", filekey);
		para.put("typecode", code);
		para.put("typename", type);
		final String tableName = new NameHandler().getTableName(MyClassLoader.getClassByScn(subclassname).getSimpleName());
		String sql=new SQL(){{
			SELECT("*");
		    FROM(tableName);
		    WHERE("businessKey=#{businessKey}");
		    if (StringUtil.isNotEmpty(filekey)) {
		        WHERE("ID=#{filekey}");
		    }
		    if (StringUtil.isNotEmpty(code)) {
		        WHERE("LAST_NAME=#{typecode}");
		    }
		    if (StringUtil.isNotEmpty(type)) {
			    WHERE("LAST_NAME=#{typename}");
			}
			}}.toString();
		dataGrid=this.commonService.getDataGridReturn(dataGrid,MyClassLoader.getClassByScn(subclassname),sql,para,true);
		TagUtil.datagrid(response, dataGrid);
	}
	/**
	 * 
	* @Title: getInitAllTables  
	* @Description: 初始化表字段和表名到缓存
	* @param     参数  
	* @return void    返回类型  
	* @throws
	 */
	@RequestMapping(value = "initAllTables")
	public void initAllTables(HttpServletRequest request, HttpServletResponse response) {
		String tableName=request.getParameter("tableName")==null?"":request.getParameter("tableName");
		systemService.getInitAllTables(tableName);
	}
	/**
	 * 
	* @Title: initAllTypeGroups  
	* @Description: 初始化数据字典到缓存
	* @param     参数  
	* @return void    返回类型  
	* @throws
	 */
	@RequestMapping(value = "initAllTypeGroups")
	public void initAllTypeGroups(HttpServletRequest request, HttpServletResponse response) {
		systemService.initAllTypeGroups();
	}
	/**
	 * 
	* @Title: getDicForCodes 
	* @Description: 根据字典代码获取数据字典内容
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDicForCodes")
	@ResponseBody
	public  AjaxJson getDicForCodes( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Map dicMap=new HashMap();
		String dicCodes=request.getParameter("dicCodes")==null?"":request.getParameter("dicCodes");
		if(dicCodes.equals("")){
			j.setSuccess(false);
			j.setMsg("字典代码串不能为空!");
			return j;
		}
		String codeArr[]=dicCodes.split(",");
		for(String code:codeArr){
			dicMap.put(code, cache.getCache(code, List.class));
		}
		j.setObj(dicMap);
		j.setSuccess(true);
		j.setMsg("获取成功!");
		return j;
	}
}
